#!/usr/bin/python3

import requests
import re
import os
import sys


# 获取百度图图片
def download_baidu_img(search_url, search_word, pn, base_dir):
    req_url = search_url + "&pn=" + str(pn) + "&word=" + search_word
    print(req_url)
    req = requests.get(req_url)
    content = req.content
    print(content)
    ret = req.text

    # re.findall('表达式', '针对的对象')
    # "objURL":"http://b-ssl.duitang.com/uploads/item/201712/09/20171209095824_2J4Se.jpeg"
    # .*表示匹配任意不换行的字符 ？非贪婪匹配
    # ()表示要获取
    result = re.findall('"objURL":"(.*?)"', ret)
    print(result)

    filr_dir = base_dir + word
    if os.path.exists(filr_dir) is False:
        os.mkdir(filr_dir)

    for i in result:
        print(i)
        split = i.split("/")
        file_name = split[len(split) - 1]
        file_name = file_name.replace('?', '_')
        file_name = file_name
        end = re.search('(.jpg|.png|.jpeg|.gif)$', i)
        if end is None:
            file_name = file_name + ".jpg"
        print(file_name)
        file_path = filr_dir + "/" + file_name
        try:

            with open(file_path, 'wb') as f:
                r = requests.get(i)
                f.write(r.content)
        except:
            print("request error url:" + i)


# 1.访问网页，获取图片URL
word = input("请输入图片关键字：")

n = 20
i = 0
root_dir = "D:/long655113/picture/百度图片/"
url = "http://image.baidu.com/search/flip?tn=baiduimage&ie=utf-8&gsm" \
          "=&ct=&ic=0&lm=-1&width=0&height=0"
while i < n:
    pn = i * 20
    download_baidu_img(url, word, pn, root_dir)
    i = i + 1

